# -*- coding: utf-8 -*-

import os
import Queue
from threading import Thread
from time import sleep

from xnotifier import notifier
from xnotifier import cfg
import xchat

join_worker = None
join_queue = Queue.Queue()


cores = cfg.cores 
rcores= cfg.rcores


def xreal_name(nick):
    users = xchat.get_list("users")
    for u in users:
        #print u.nick, u.host, u.prefix, u.realname
        if nick == u.nick:
            return u.realname
        
def join_thread():
    while True:
        nick = join_queue.get()
        join_queue.task_done()
        sleep(12)
        rname = xreal_name(nick)
        who,rwho = user_filter(nick, rname)
        if rwho:
            notifier.mail_notify("*by real* %s %s!(%s)"%(nick, "Join",rname))
            continue
        if who:
            notifier.mail_notify("*by nick* %s %s!(%s)"%(nick, "Join",rname) )
            continue

        
def join_defer(nick):
    join_queue.put(nick) 



def user_filter(nick, rname):
    if rname is not None:
        rwho = [ rname for one in rcores if one.lower() in rname.lower()]
    else:
        rwho = []
    who = [ nick for one in cores if one.lower() in nick.lower()]
    return who,rwho

#
# sender’s username in word[0]
# user’s mode in word[2], 
# the message is word[1]. 
def on_message(word, word_eol, userdata):
    #print word, word_eol, userdata
# ['openstackgerrit', 
#   'Shuangtai Tian proposed a change ...etrics  https://review.openstack.org/35767']
# 
    nick = word[0]
    rname = xreal_name(nick)
    who,rwho = user_filter(nick, rname)
        
    if rwho:
        notifier.mail_notify("*by real* %s is active!(%s)!"%(nick,rname))
        return xchat.EAT_PLUGIN
    
    if who:
        notifier.mail_notify("*by nick* %s is active!(%s)!"%(nick,rname))
        return xchat.EAT_PLUGIN

    return xchat.EAT_NONE 



def server_cb(word, word_eol, userdata):
# Join example
# [':vartom11113!~vartom@131.207.254.198', 'JOIN', '#openstack-dev'] 
# [':vartom11113!~vartom@131.207.254.198 JOIN #openstack-dev', 'JOIN #openstack-dev', '#openstack-dev']

# Quit example:
# [':vartom11112!~vartom@131.207.209.42', 'QUIT', ':Ping', 'timeout:', '264', 'seconds'] 
# [':garyk!~Adium@80.179.96.113.static.012.net.il', 'QUIT', ':Remote', 'host', 'closed', 'the', 'connection']
# [':gmurphy!gm@nat/redhat/x-patfglgsjfracftn', 'QUIT', ':Quit:', 'Ex-Chat']
#    print word, word_eol 
    
    
    action = word[1]
    #':garyk!~Adium@80.179.96.113.static.012.net.il' => :garyk => garyk
    nick = word[0].split("!")[0].split(":")[1]

    rname = xreal_name(nick)
    who,rwho = user_filter(nick, rname)

    if action in ["JOIN"]:
        xchat.command("who %s "%nick)
        join_defer(nick)
        return xchat.EAT_NONE 

    if rwho and  action in ["QUIT"]:
        notifier.mail_notify("*by real* %s %s!(%s)"%(nick, action,rname))
        return xchat.EAT_NONE 
 
    if who and  action in ["QUIT"]:
        notifier.mail_notify("*by nick* %s %s!(%s)"%(nick, action,rname) )
        return xchat.EAT_NONE 

    return xchat.EAT_NONE 


def start_notifier():

    notifier.init()
    
    join_worker = Thread(target = join_thread)
    join_worker.start()
    
    # some one leave or online
    xchat.hook_server("Quit", server_cb)
    xchat.hook_server("Join", server_cb)

    # the nick is said, it is a "Channel Msg Hilight" event rather than a "Channel Message" event.
    xchat.hook_print('Channel Message', on_message)
    xchat.hook_print('Channel Msg Hilight', on_message)

    #testing
    notifier.mail_notify("plugin testing!!")
